package com.fdq.bigevent.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public class AliOss {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    private static EnvironmentVariableCredentialsProvider credentialsProvider;

    static {
        try {
            credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }

    // 填写Bucket名称，例如examplebucket。
    private static String bucketName = "fdqbucket";
    // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
    private static String objectName = "big-event/";

    // 创建OSSClient实例。
    private static OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

    public static String upload(String filename, MultipartFile file) throws IOException {
        String destination = objectName + filename;
        ossClient.putObject(bucketName,destination,file.getInputStream());
        String url = "https://fdqbucket.oss-cn-beijing.aliyuncs.com/big-event/"+filename;
        return url;
    }





    public AliOss() throws ClientException {
    }
}
